package com.hzw.saas.common.verify.aspect;

import com.anji.captcha.model.common.ResponseModel;
import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService;
import com.hzw.saas.common.config.util.AssertUtil;
import com.hzw.saas.common.util.SpringELUtils;
import cn.hutool.core.util.StrUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 拼图切面
 *
 * @Date 2021/6/28 4:50 下午
 * @Created by sonam
 */
@Aspect
@Component
@Slf4j
@RequiredArgsConstructor
@Order(1)
public class PuzzleVerifyAspect {

    private final CaptchaService captchaService;

    @Value("${saas.verify.puzzleVerify}")
    private boolean puzzleVerifyFlag;

    @Before("@annotation(puzzleVerify)")
    public void before(JoinPoint joinPoint, PuzzleVerify puzzleVerify) {
        if(!puzzleVerifyFlag) {
            log.debug("skip puzzleVerify ...");
            return;
        }

        String captchaVerification = SpringELUtils.getSpelValue(joinPoint, puzzleVerify.captchaVerification(), String.class);
        String pointJson = SpringELUtils.getSpelValue(joinPoint, puzzleVerify.pointJson(), String.class);
        log.debug("check params: {}", captchaVerification);
        AssertUtil.assertThrow("验证失败，请输入正确的参数", StrUtil.isBlank(captchaVerification) || StrUtil.isBlank(pointJson));

        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaVerification(captchaVerification.concat("---").concat(pointJson));

        ResponseModel response = captchaService.verification(captchaVO);
        if(response.isSuccess() == false){
            //验证码校验失败，返回信息告诉前端
            switch (response.getRepCode()) {
                case "9999":
                    AssertUtil.assertThrow("服务器内部异常", true);
                case "0011":
                    AssertUtil.assertThrow("参数不能为空", true);
                case "6110":
                    AssertUtil.assertThrow("验证码已失效，请重新获取", true);
                case "6111":
                    AssertUtil.assertThrow("验证失败", true);
                case "6112":
                    AssertUtil.assertThrow("获取验证码失败,请联系管理员", true);
                case "6113":
                    AssertUtil.assertThrow("底图未初始化成功，请检查路径", true);
                case "6201":
                    AssertUtil.assertThrow("get接口请求次数超限，请稍后再试!", true);
                case "6206":
                    AssertUtil.assertThrow("无效请求，请重新获取验证码", true);
                case "6202":
                    AssertUtil.assertThrow("接口验证失败数过多，请稍后再试", true);
                case "6204":
                    AssertUtil.assertThrow("check接口请求次数超限，请稍后再试!", true);
            }
        }


    }

}
